package com.m3958.firstgwt.server.servlet;


import static nl.captcha.Captcha.NAME;

import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.captcha.Captcha;
import nl.captcha.noise.StraightLineNoiseProducer;
import nl.captcha.servlet.CaptchaServletUtil;
import nl.captcha.text.producer.DefaultTextProducer;
import nl.captcha.text.renderer.DefaultWordRenderer;

import com.google.inject.Singleton;

@Singleton
public class MySimpleCaptchaServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;

    private static int _width = 200;
    private static int _height = 50;
    
    private static final List<Color> COLORS = new ArrayList<Color>(2);
    private static final List<Font> FONTS = new ArrayList<Font>(3);
    
    static {
        COLORS.add(Color.GRAY);
        COLORS.add(Color.BLACK);
        COLORS.add(Color.ORANGE);
        COLORS.add(Color.BLUE);

        FONTS.add(new Font("Geneva", Font.ITALIC, 24));
        FONTS.add(new Font("Courier", Font.PLAIN, 24));
        FONTS.add(new Font("Arial", Font.PLAIN, 24));
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    	if (getInitParameter("captcha-height") != null) {
    		_height = Integer.valueOf(getInitParameter("captcha-height"));
    	}
    	
    	if (getInitParameter("captcha-width") != null) {
    		_width = Integer.valueOf(getInitParameter("captcha-width"));
    	}
    }
    
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
//        ColoredEdgesWordRenderer wordRenderer = new ColoredEdgesWordRenderer(COLORS, FONTS);
    	if(req.getParameter("_width") != null){
    		_width = Integer.parseInt(req.getParameter("_width"));
    		if(_width>200)_width=150;
    	}
    	if(req.getParameter("_height") != null){
    		_height = Integer.parseInt(req.getParameter("_height"));
    		if(_height>150)_height=70;
    	}
        Captcha captcha = new Captcha.Builder(_width, _height).addText(
        		new DefaultTextProducer(), 
        		new DefaultWordRenderer(COLORS, FONTS)
        		)
//                .gimp()
                .addNoise(new StraightLineNoiseProducer(Color.PINK,2))
//                .addBackground(new GradiatedBackgroundProducer())
                .build();
        req.getSession().setAttribute(NAME, captcha);
        CaptchaServletUtil.writeImage(resp, captcha.getImage());
    }
}
